package com.guijq.selfcode.deadlock;

/**
 * @author yangjf
 * @time 2019-05-10 10:03
 */
public class DeadlockDemo extends Thread {
    private BaseObj first;
    private BaseObj second;

    public DeadlockDemo(String name, BaseObj first, BaseObj second) {
        super(name);
        this.first = first;
        this.second = second;
    }

    public void reentrantLock() throws InterruptedException {
        first.lock();
        System.out.println(String.format("%s 持有:%s 对象锁，等待获取:%s对象锁", this.getName(), first, second));
        second.lock();
        first.unlock();
        second.unlock();
    }
    @Override
    public void run() {
        try {
            reentrantLock();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BaseObj one = new BaseObj();
        BaseObj two = new BaseObj();

        DeadlockDemo thread1 = new DeadlockDemo("Thread1", one, two);
        DeadlockDemo thread2 = new DeadlockDemo("Thread2", two, one);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
    }
}
